'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Loader2 } from 'lucide-react'
import ReactECharts from 'echarts-for-react'

interface HRVData {
  timestamp: number
  hrv: number
  stress: number
  vascularAging: number
  heartRate: number
  highBP: number
  lowBP: number
}

interface HRVChartProps {
  userId: string
  selectedDate: string
}

export function HRVChart({ userId, selectedDate }: HRVChartProps) {
  const [hrvData, setHrvData] = useState<HRVData[]>([])
  const [loading, setLoading] = useState(false)

  // 获取HRV数据
  const fetchHRVData = async () => {
    try {
      // 数据库中的时间戳是本地时间戳，直接构造本地时间范围
      const selectedDateObj = new Date(selectedDate)
      
      // 构造本地时间的开始和结束时间戳
      const startDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0)
      const endDate = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0)
      
      console.log('HRV查询时间范围:', {
        selectedDate,
        startDate: startDate.toLocaleString('zh-CN'),
        endDate: endDate.toLocaleString('zh-CN'),
        startDateISO: startDate.toISOString(),
        endDateISO: endDate.toISOString(),
        startTimestamp: startDate.getTime(),
        endTimestamp: endDate.getTime()
      })

      const response = await fetch(`/api/health?userId=${userId}&dataType=hrv&startDate=${startDate.toISOString()}&endDate=${endDate.toISOString()}`)
      
      if (!response.ok) {
        throw new Error('Failed to fetch HRV data')
      }

      const data = await response.json()
      console.log('HRV API响应:', data)

      // 提取HRV数据
      const logs = data.data?.logs || data.logs || []
      console.log('HRV 提取的logs:', {
        logsLength: logs.length,
        firstLog: logs[0] || null,
        lastLog: logs[logs.length - 1] || null
      })

      const processedData = processHRVData(logs)
      console.log('处理后的HRV数据:', {
        originalLogsCount: logs.length,
        processedDataCount: processedData.length,
        firstProcessedData: processedData[0] || null,
        lastProcessedData: processedData[processedData.length - 1] || null
      })
      setHrvData(processedData)
    } catch (error) {
      console.error('获取HRV数据失败:', error)
      setHrvData([])
    }
  }

  // 处理HRV数据
  const processHRVData = (logs: any[]): HRVData[] => {
    const hrvPoints: HRVData[] = []
    
    logs.forEach((log) => {
      const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data

      // 处理时间戳：优先使用logData中的ts，如果没有则使用log的timestamp
      let timestamp = parseInt(logData.ts) || parseInt(log.timestamp)
      
      // 如果时间戳是10位（秒级），转换为13位（毫秒级）
      if (timestamp < 10000000000) {
        timestamp = timestamp * 1000
      }
      
      // 检查时间戳是否在合理范围内（2020-2070年之间）
      const minValidTimestamp = new Date('2020-01-01').getTime()
      const maxValidTimestamp = new Date('2070-12-31').getTime()
      
      if (timestamp < minValidTimestamp || timestamp > maxValidTimestamp) {
        console.warn('跳过无效时间戳:', {
          originalTimestamp: logData.ts || log.timestamp,
          convertedTimestamp: timestamp,
          timestampDate: new Date(timestamp).toISOString()
        })
        return
      }
      
      // 提取HRV相关数据
      const hrvValue = parseInt(logData.hrv) || 0
      const stressValue = parseInt(logData.stress) || 0
      
      if (hrvValue > 0 || stressValue > 0) {
        hrvPoints.push({
          timestamp,
          hrv: hrvValue,
          stress: stressValue,
          vascularAging: parseInt(logData.vascularAging) || 0,
          heartRate: parseInt(logData.heartRate) || 0,
          highBP: parseInt(logData.highBP) || 0,
          lowBP: parseInt(logData.lowBP) || 0
        })
      }
    })

    return hrvPoints.sort((a, b) => a.timestamp - b.timestamp)
  }

  // 生成HRV图表配置
  const generateHRVChart = () => {
    if (hrvData.length === 0) return null

    // 准备图表数据 - 不聚合，每个数据点单独显示
    const hrvSeriesData: any[] = []
    const stressSeriesData: [number, number][] = []

    hrvData.forEach(data => {
      // 根据HRV值确定活力状态和颜色
      let vitalityStatus = ''
      let pointColor = ''
      
      if (data.hrv > 40) {
        vitalityStatus = '活力满满'
        pointColor = '#22c55e' // 绿色
      } else if (data.hrv >= 20) {
        vitalityStatus = '活力正常'
        pointColor = '#f59e0b' // 橙色
      } else {
        vitalityStatus = '活力不佳'
        pointColor = '#ef4444' // 红色
      }

      hrvSeriesData.push({
        value: [data.timestamp, data.hrv],
        itemStyle: {
          color: pointColor
        },
        vitalityStatus: vitalityStatus
      })
      
      stressSeriesData.push([data.timestamp, data.stress])
    })

    // 计算Y轴范围
    const hrvValues = hrvData.map(d => d.hrv).filter(v => v > 0)
    const stressValues = hrvData.map(d => d.stress).filter(v => v > 0)
    
    const hrvMin = hrvValues.length > 0 ? Math.min(...hrvValues) : 0
    const hrvMax = hrvValues.length > 0 ? Math.max(...hrvValues) : 100
    const stressMin = stressValues.length > 0 ? Math.min(...stressValues) : 0
    const stressMax = stressValues.length > 0 ? Math.max(...stressValues) : 100

    return {
      title: {
        text: 'HRV与压力分析',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'bold' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          if (params && params.length > 0) {
            const timestamp = params[0].value ? params[0].value[0] : params[0].data.value[0]
            const time = new Date(timestamp).toLocaleString('zh-CN', {
              year: 'numeric',
              month: 'numeric',
              day: 'numeric',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            })
            
            let tooltipContent = `${time}<br/>`
            
            params.forEach((param: any) => {
              if (param.seriesName === 'HRV') {
                const value = param.value ? param.value[1] : param.data.value[1]
                const vitalityStatus = param.data?.vitalityStatus || ''
                if (value > 0) {
                  tooltipContent += `HRV: ${value}ms<br/>`
                  if (vitalityStatus) {
                    tooltipContent += `状态: ${vitalityStatus}<br/>`
                  }
                }
              } else if (param.seriesName === '压力') {
                const value = param.value ? param.value[1] : param.data[1]
                if (value > 0) {
                  tooltipContent += `压力: ${value}<br/>`
                }
              }
            })
            
            return tooltipContent
          }
          return ''
        }
      },
      legend: {
        data: ['HRV', '压力'],
        top: 30
      },
      xAxis: {
        type: 'time',
        axisLabel: {
          formatter: (value: number) => {
            const date = new Date(value)
            return date.getHours().toString().padStart(2, '0') + ':00'
          }
        },
        min: () => {
          // 设置X轴范围为选择日期的00:00到24:00
          const selectedDateObj = new Date(selectedDate)
          return new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate(), 0, 0, 0, 0).getTime()
        },
        max: () => {
          const selectedDateObj = new Date(selectedDate)
          return new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), selectedDateObj.getDate() + 1, 0, 0, 0, 0).getTime()
        }
      },
      yAxis: [
        {
          type: 'value',
          name: 'HRV',
          position: 'left',
          min: Math.max(0, hrvMin - 10),
          max: hrvMax + 10,
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            lineStyle: {
              color: '#22c55e'
            }
          }
        },
        {
          type: 'value',
          name: '压力',
          position: 'right',
          min: Math.max(0, stressMin - 5),
          max: stressMax + 5,
          axisLabel: {
            formatter: '{value}'
          },
          axisLine: {
            lineStyle: {
              color: '#ef4444'
            }
          }
        }
      ],
      series: [
        {
          name: 'HRV',
          type: 'line',
          yAxisIndex: 0,
          data: hrvSeriesData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8, // 增大数据点以更好显示颜色
          lineStyle: {
            color: '#22c55e', // 线条保持绿色
            width: 2
          }
          // 移除固定的itemStyle，让每个数据点使用自己的颜色
        },
        {
          name: '压力',
          type: 'line',
          yAxisIndex: 1,
          data: stressSeriesData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color: '#ef4444',
            width: 2
          },
          itemStyle: {
            color: '#ef4444'
          }
        }
      ]
    }
  }

  // 获取统计信息
  const getStatistics = () => {
    if (hrvData.length === 0) {
      return {
        title: 'HRV统计',
        stats: [
          { label: '数据点', value: '0' },
          { label: '平均HRV', value: '无数据' },
          { label: '平均压力', value: '无数据' },
          { label: 'HRV范围', value: '无数据' }
        ]
      }
    }

    const hrvValues = hrvData.map(d => d.hrv).filter(v => v > 0)
    const stressValues = hrvData.map(d => d.stress).filter(v => v > 0)
    
    const avgHRV = hrvValues.length > 0 ? Math.round(hrvValues.reduce((sum, v) => sum + v, 0) / hrvValues.length) : 0
    const avgStress = stressValues.length > 0 ? Math.round(stressValues.reduce((sum, v) => sum + v, 0) / stressValues.length) : 0
    const minHRV = hrvValues.length > 0 ? Math.min(...hrvValues) : 0
    const maxHRV = hrvValues.length > 0 ? Math.max(...hrvValues) : 0

    // 统计活力状态分布
    const excellentCount = hrvValues.filter(v => v > 40).length // 活力满满
    const normalCount = hrvValues.filter(v => v >= 20 && v <= 40).length // 活力正常
    const poorCount = hrvValues.filter(v => v < 20).length // 活力不佳
    
    let overallVitality = '无数据'
    if (hrvValues.length > 0) {
      if (excellentCount > normalCount && excellentCount > poorCount) {
        overallVitality = '活力满满'
      } else if (normalCount > poorCount) {
        overallVitality = '活力正常'
      } else {
        overallVitality = '活力不佳'
      }
    }

    return {
      title: 'HRV统计',
      stats: [
        { label: '数据点', value: hrvData.length.toString() },
        { label: '平均HRV', value: avgHRV > 0 ? `${avgHRV}ms` : '无数据' },
        { label: '活力状态', value: overallVitality },
        { label: 'HRV范围', value: minHRV > 0 && maxHRV > 0 ? `${minHRV} - ${maxHRV}ms` : '无数据' }
      ]
    }
  }

  // 数据获取
  useEffect(() => {
    if (!userId || !selectedDate) return

    setLoading(true)
    
    const fetchData = async () => {
      await fetchHRVData()
      setLoading(false)
    }

    fetchData()
  }, [userId, selectedDate])

  const statistics = getStatistics()
  const chartConfig = generateHRVChart()

  return (
    <div className="space-y-4">
      {/* 图表区域 */}
      <Card>
        <CardHeader>
          <CardTitle>HRV与压力分析</CardTitle>
          <CardDescription>
            显示心率变异性(HRV)和压力水平的变化趋势。HRV数据点颜色：绿色(&gt;40ms活力满满)，橙色(20-40ms活力正常)，红色(&lt;20ms活力不佳)
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin" />
              <span className="ml-2">加载中...</span>
            </div>
          ) : chartConfig ? (
            <ReactECharts
              option={chartConfig}
              style={{ width: '100%', height: '400px' }}
              opts={{ renderer: 'canvas' }}
            />
          ) : (
            <div className="flex items-center justify-center h-64 text-gray-500">
              <div className="text-center">
                <p className="text-lg font-medium">暂无数据</p>
                <p className="text-sm">该日期没有HRV数据</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 统计信息 */}
      <Card>
        <CardHeader>
          <CardTitle>{statistics.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {statistics.stats.map((stat, index) => (
              <div key={index} className="text-center p-3 bg-gray-50 rounded-lg">
                <div className="text-2xl font-bold text-gray-900">{stat.value}</div>
                <div className="text-sm text-gray-600">{stat.label}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
